package com.xinzhi.service.impl;

import com.xinzhi.mapper.ReceiptRecordMapper;
import com.xinzhi.mapper.TransferRecordMapper;
import com.xinzhi.mapper.TransferUserMapper;
import com.xinzhi.pojo.dto.ReceiptRecord;
import com.xinzhi.pojo.TransferRecord;
import com.xinzhi.pojo.TransferUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.math.BigDecimal;
import java.sql.Timestamp;

@Service
@Transactional
public class TransferService {

    @Autowired
    private TransferRecordMapper transferRecordMapper;

    @Autowired
    private ReceiptRecordMapper receiptRecordMapper;

    @Autowired
    private TransferUserMapper transferUserMapper;

    // 默认本地货币为人民币
    private static final String LOCAL_CURRENCY = "CNY";
    private static final String BANK_ACCOUNT_REGEX = "^\\d{16,19}$";


    @Transactional
    public String initiateTransfer(String senderBankAccount, String receiverName, String receiverBankAccount,
                                   BigDecimal amount, BigDecimal amountInCurrency, BigDecimal exchangeRate,
                                   BigDecimal fee, String description, String currency) {
        if (!isValidBankAccount(senderBankAccount)) {
            throw new RuntimeException("发送者银行卡号格式不正确：" + senderBankAccount);
        }
        // 查询发送者信息
        TransferUser sender = transferUserMapper.selectByBankAccount(senderBankAccount);
        if (sender == null) {
            throw new RuntimeException("发送者账户不存在：" + senderBankAccount);
        }

        // 创建转账记录
        TransferRecord transferRecord = new TransferRecord();
        transferRecord.setSenderBankAccount(senderBankAccount);
        transferRecord.setReceiverName(receiverName); // 设置接收者姓名
        transferRecord.setReceiverBankAccount(receiverBankAccount); // 设置接收者银行账号
        transferRecord.setAmount(amount);
        transferRecord.setAmountInCurrency(amountInCurrency);
        transferRecord.setExchangeRate(exchangeRate);
        transferRecord.setTransferTime(new Timestamp(System.currentTimeMillis()));

        transferRecord.setFee(fee);
        transferRecord.setDescription(description);
        transferRecord.setCurrency(currency);

        transferRecordMapper.insert(transferRecord);

        // 更新发送者余额
        BigDecimal senderNewBalance = sender.getBalance().subtract(amount);
        if (senderNewBalance.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("发送者余额不足");
        }
        sender.setBalance(senderNewBalance);
        transferUserMapper.updateBalance(sender.getId(), senderNewBalance); // 更新余额

        return senderBankAccount;
    }
    @Transactional
    public void processTransfer(Long transferId) {
        TransferRecord transferRecord = transferRecordMapper.selectById(transferId);
        if (transferRecord == null) {
            throw new RuntimeException("转账记录不存在");
        }

        // 更新转账记录状态为完成
        transferRecord.setStatus("completed");
        transferRecordMapper.updateById(transferRecord);
        // 创建收款记录
        ReceiptRecord receiptRecord = new ReceiptRecord();
        receiptRecord.setSenderBankAccount(transferRecord.getSenderBankAccount());
        receiptRecord.setReceiverName(transferRecord.getReceiverName());
        receiptRecord.setReceiverBankAccount(transferRecord.getReceiverBankAccount());
        receiptRecord.setAmount(transferRecord.getAmount());
        receiptRecord.setCurrency(LOCAL_CURRENCY);
        receiptRecord.setReceiptTime(new Timestamp(System.currentTimeMillis()));
        receiptRecord.setStatus("received");
        receiptRecordMapper.insert(receiptRecord);
    }
    private boolean isValidBankAccount(String bankAccount) {
        Pattern pattern = Pattern.compile(BANK_ACCOUNT_REGEX);
        Matcher matcher = pattern.matcher(bankAccount);
        return matcher.matches();
    }

}
